import { mqttService, topics } from './MQTTService';
import { chessGameService, ChessCamp } from './ChessGameService';
import { userService } from './UserService';

// 初始化象棋消息处理器
export function initChessMessageHandler() {
  console.log('初始化象棋消息处理器...');
  
  // 监听MQTT消息
  if (!mqttService.client) {
    console.error('MQTT客户端未初始化，无法监听消息');
    return;
  }
  
  // 先移除之前的消息监听，避免重复监听
  mqttService.client.removeAllListeners('message');
  
  mqttService.client.on('message', (topic, message) => {
    try {
      const messageStr = message.toString();
      
      // 过滤出象棋相关消息
      if (topic === topics.GAME_MATCHING) {
        console.log(`收到象棋匹配频道消息 [${topic}]: ${messageStr}`);
        
        const parsedMessage = JSON.parse(messageStr);
        
        // 处理象棋匹配消息
        handleChessMatchingMessage(parsedMessage);
      }
      
      // 处理象棋游戏房间消息
      if (topic.includes(topics.GAME_ROOM) && topic.endsWith('_chess')) {
        console.log(`收到象棋游戏消息 [${topic}]: ${messageStr}`);
        
        const parsedMessage = JSON.parse(messageStr);
        chessGameService.handleMQTTMessage(topic, parsedMessage);
      }
      
    } catch (error) {
      console.error('处理象棋消息时出错:', error);
    }
  });
  
  // 确保订阅了匹配频道
  mqttService.subscribe(topics.GAME_MATCHING);
  
  console.log('象棋消息处理器初始化完成');
}

// 处理象棋匹配消息
function handleChessMatchingMessage(message) {
  const myUserId = userService.userId.value;
  console.log(`处理象棋匹配消息，消息类型: ${message.type}, 我的用户ID: ${myUserId}`);
  
  // 忽略测试消息
  if (message.type === 'test') {
    console.log('收到测试消息，忽略');
    return;
  }
  
  switch (message.type) {
    case 'request_chess_match':
      console.log(`收到象棋匹配请求消息，发送者ID: ${message.userId}, 发送者用户名: ${message.username}`);
      console.log(`我的状态: ${chessGameService.status.value}, 我的ID: ${myUserId}`);
      
      // 如果不是自己发送的匹配请求，且自己也在匹配中，则处理
      if (message.userId !== myUserId && chessGameService.status.value === 'matching') {
        console.log(`处理象棋匹配请求: ${message.username} (${message.userId})`);
        
        // 创建房间数据
        const roomId = `chess_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
        const currentTime = new Date().getTime();
        const isFirstPlayerRed = Math.random() >= 0.5;
        
        const roomData = {
          roomId,
          players: [
            {
              userId: myUserId,
              username: userService.username.value,
              camp: isFirstPlayerRed ? ChessCamp.RED : ChessCamp.BLACK
            },
            {
              userId: message.userId,
              username: message.username,
              camp: isFirstPlayerRed ? ChessCamp.BLACK : ChessCamp.RED
            }
          ],
          currentTurn: isFirstPlayerRed ? myUserId : message.userId, // 红方先行
          startTime: currentTime,
          lastMoveTime: currentTime
        };
        
        console.log('创建象棋房间数据:', roomData);
        
        // 先处理自己的匹配成功，再发送匹配成功消息
        chessGameService.handleMatchSuccess(roomData);
        
        // 发送匹配成功消息
        mqttService.publish(topics.GAME_MATCHING, {
          type: 'chess_match_success',
          room: roomData,
          timestamp: currentTime
        }).then(() => {
          console.log('匹配成功消息已发送');
        }).catch(error => {
          console.error('发送匹配成功消息失败:', error);
        });
      } else {
        console.log(`忽略匹配请求 - 是否自己发送: ${message.userId === myUserId}, 当前状态: ${chessGameService.status.value}`);
      }
      break;
      
    case 'cancel_chess_match':
      console.log(`收到取消象棋匹配消息，发送者ID: ${message.userId}`);
      // 不需要特殊处理
      break;
      
    case 'chess_match_success':
      console.log('收到象棋匹配成功消息，房间信息:', message.room);
      // 如果是自己的匹配成功消息，则处理
      const players = message.room.players;
      const isMyMatch = players.some(player => player.userId === myUserId);
      
      if (isMyMatch && chessGameService.status.value !== 'playing') {
        console.log('这是我的象棋匹配，处理匹配成功');
        const result = chessGameService.handleMatchSuccess(message.room);
        console.log(`象棋匹配成功处理结果: ${result ? '成功' : '失败'}`);
      } else {
        console.log(`不处理匹配成功消息 - 是我的匹配: ${isMyMatch}, 当前状态: ${chessGameService.status.value}`);
      }
      break;
      
    default:
      console.warn('未知的象棋匹配消息类型:', message.type);
  }
} 